package cn.hrms.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hrms.domain.User;
import cn.hrms.domain.dto.UserLoginBody;
import cn.hrms.domain.dto.UserRegisterBody;
import cn.hrms.domain.web.LoginInfo;
import cn.hrms.exception.ServiceException;
import cn.hrms.mapper.UserMapper;
import cn.hrms.service.IUserService;
import cn.hrms.utils.DateUtils;
import cn.hrms.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;


/**
 * 用户服务实现类
 *
 * @author xiaokai54
 * @date 2024/12/17
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements IUserService {
	private final UserMapper userMapper;

	@Override
	public LoginInfo login(UserLoginBody loginBody) {
		// 查找用户
		User user = this.getUserByUserName(loginBody.getUsername());
		if (user == null){
			throw new ServiceException("用户不存在");
		}
		// 判断密码，这里使用到了sa-token
		if (!BCrypt.checkpw(loginBody.getPassword(), user.getPassword())) {
			throw new ServiceException("密码错误");
		}
		// 用户判断
		if (User.USER_DELETED.equals(user.getDelFlag())) {
			throw new ServiceException("用户已删除");
		}
		if (User.USER_FAILED.equals(user.getStatus())) {
			throw new ServiceException("用户已禁用");
		}

		StpUtil.login(String.valueOf(user.getUserId()));
		StpUtil.getSession().set("username", user.getRealName());
		StpUtil.getSession().set("userEmpNo", user.getEmpId());
		return LoginInfo.builder()
				.userId(user.getUserId())
				.empId(user.getEmpId())
				.username(user.getUsername())
				.realName(user.getRealName())
				.token(StpUtil.getTokenValue()).build();
	}

	@Override
	public void register(UserRegisterBody registerBody) {
		// 判断用户名是否存在
		if (this.getUserByUserName(registerBody.getUsername()) != null) {
			throw new ServiceException("用户名已存在");
		}
		// 判断真实姓名是否存在，不存在就生成默认值
		String realName = StringUtils.isBlank(registerBody.getRealName()) ? "请及时设置真实姓名" : registerBody.getRealName();
		User user = new User();
		user.setUsername(registerBody.getUsername());
		user.setRealName(realName);
		user.setEmail(registerBody.getEmail());
		user.setPhone(registerBody.getPhone());
		user.setSex(registerBody.getSex());
		user.setPassword(BCrypt.hashpw(registerBody.getPassword()));
		user.setStatus("0");
		user.setDelFlag("0");
		user.setCreateUser(registerBody.getUsername());
		user.setCreateTime(DateUtils.getNowDate());
		this.insertUser(user);
	}

	@Override
	public User selectUserById(long userId) {
		return userMapper.selectUserById(userId);
	}

	public User getUserByUserName(String username) {
		return userMapper.selectUserByUsername(username);
	}

	public void insertUser(User user) {
		userMapper.insertUser(user);
	}
}
